import { toast, showLoading, hideLoading } from "@/utils/utils";

const devUrl =  "https://test-wx-applet.51jzt.com/prod-api";

import terminateRequest from "@/store/modules/terminateRequest";
import { useTokenStore } from "@/store/modules/token/index";

export const request = ({
  method,
  data,
  url,
  isLoading,
  timeout,
  responseType,
}) => {
  const upperMethod = method && method.toLocaleUpperCase(),
    contentType =
      upperMethod === "POST"
        ? "application/json"
        : "application/x-www-form-urlencoded";
  let promiseRequest = null;
  return new Promise((resolve, reject) => {
    isLoading && showLoading();
    promiseRequest = uni.request({
      url: `${devUrl}/${url}`,
      method: upperMethod || "GET",
      header: {
        Authorization: uni.getStorageSync("token").value,
        "Content-Type": contentType,
      },
      data: data || {},
      timeout: timeout || 10000,
      responseType: responseType || "text",
      success(res) {
        const {
          data: { code, data: data2, msg },
        } = res;
        if (code === 401 || code === 550) {
          reject(res);
          uni.removeStorageSync("token");
          uni.removeStorageSync("tenantId");
          const tokenStore = useTokenStore();
          tokenStore.syncToken();
          return toast(!msg ? "登录过期" : msg);
        }
        if (code !== 200) {
          if (code === 500 && !data2) {
            reject(res);
            return toast(!msg ? "服务器异常" : msg);
          }
          if (code === 530 || code === 535) {
            reject(res);
          }
        }
        resolve(res.data);
      },
      fail(err) {
        if (err.errMsg != "request:fail abort") {
          toast(err.errMsg);
        }
        reject(err);
      },
      complete() {
        isLoading && hideLoading();
      },
    });
    terminateRequest().$setAbortReq(url, promiseRequest);
  });
};
